<!DOCTYPE html>
<html style="display: none;" lang="zh">
    <head>
    <meta charset="utf-8">
    <!--
        © Material Theme
        https://github.com/viosey/hexo-theme-material
        Version: 1.5.2 -->
    <script>
        window.materialVersion = "1.5.2"
        // Delete localstorage with these tags
        window.oldVersion = [
            'codestartv1',
            '1.3.4',
            '1.4.0',
            '1.4.0b1',
            '1.5.0'
        ]
    </script>

    <!-- dns prefetch -->
    <meta http-equiv="x-dns-prefetch-control" content="on">


    <link rel="dns-prefetch" href="https://cdn1.lncld.net"/>













    <!-- Meta & Info -->
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <meta name="renderer" content="webkit">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">

    <!-- Title -->
    
    <title>
        
            JVM学习02-GC算法与种类 | 
        
        android开发者
    </title>

    <!-- Favicons -->
    <link rel="icon shortcut" type="image/ico" href="/img/favicon.png">
    <link rel="icon" href="/img/favicon.png">

    <meta name="format-detection" content="telephone=no"/>
    <meta name="description" itemprop="description" content="android开发工程师，学习，记录。">
    <meta name="keywords" content="android,java">
    <meta name="theme-color" content="#0097A7">

    <!-- Disable Fucking Bloody Baidu Tranformation -->
    <meta http-equiv="Cache-Control" content="no-transform" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />

    <!--[if lte IE 9]>
        <link rel="stylesheet" href="/css/ie-blocker.css">

        
            <script src="/js/ie-blocker.zhCN.js"></script>
        
    <![endif]-->

    <!-- Import lsloader -->
    <script>(function(){window.lsloader={jsRunSequence:[],jsnamemap:{},cssnamemap:{}};lsloader.removeLS=function(a){try{localStorage.removeItem(a)}catch(b){}};lsloader.setLS=function(a,c){try{localStorage.setItem(a,c)}catch(b){}};lsloader.getLS=function(a){var c="";try{c=localStorage.getItem(a)}catch(b){c=""}return c};versionString="/*"+(window.materialVersion||"unknownVersion")+"*/";lsloader.clean=function(){try{var b=[];for(var a=0;a<localStorage.length;a++){b.push(localStorage.key(a))}b.forEach(function(e){var f=lsloader.getLS(e);if(window.oldVersion){var d=window.oldVersion.reduce(function(g,h){return g||f.indexOf("/*"+h+"*/")!==-1},false);if(d){lsloader.removeLS(e)}}})}catch(c){}};lsloader.clean();lsloader.load=function(f,a,b,d){if(typeof b==="boolean"){d=b;b=undefined}d=d||false;b=b||function(){};var e;e=this.getLS(f);if(e&&e.indexOf(versionString)===-1){this.removeLS(f);this.requestResource(f,a,b,d);return}if(e){var c=e.split(versionString)[0];if(c!=a){console.log("reload:"+a);this.removeLS(f);this.requestResource(f,a,b,d);return}e=e.split(versionString)[1];if(d){this.jsRunSequence.push({name:f,code:e});this.runjs(a,f,e)}else{document.getElementById(f).appendChild(document.createTextNode(e));b()}}else{this.requestResource(f,a,b,d)}};lsloader.requestResource=function(b,e,a,c){var d=this;if(c){this.iojs(e,b,function(h,f,g){d.setLS(f,h+versionString+g);d.runjs(h,f,g)})}else{this.iocss(e,b,function(f){document.getElementById(b).appendChild(document.createTextNode(f));d.setLS(b,e+versionString+f)},a)}};lsloader.iojs=function(d,b,g){var a=this;a.jsRunSequence.push({name:b,code:""});try{var f=new XMLHttpRequest();f.open("get",d,true);f.onreadystatechange=function(){if(f.readyState==4){if((f.status>=200&&f.status<300)||f.status==304){if(f.response!=""){g(d,b,f.response);return}}a.jsfallback(d,b)}};f.send(null)}catch(c){a.jsfallback(d,b)}};lsloader.iocss=function(f,c,h,a){var b=this;try{var g=new XMLHttpRequest();g.open("get",f,true);g.onreadystatechange=function(){if(g.readyState==4){if((g.status>=200&&g.status<300)||g.status==304){if(g.response!=""){h(g.response);a();return}}b.cssfallback(f,c,a)}};g.send(null)}catch(d){b.cssfallback(f,c,a)}};lsloader.iofonts=function(f,c,h,a){var b=this;try{var g=new XMLHttpRequest();g.open("get",f,true);g.onreadystatechange=function(){if(g.readyState==4){if((g.status>=200&&g.status<300)||g.status==304){if(g.response!=""){h(g.response);a();return}}b.cssfallback(f,c,a)}};g.send(null)}catch(d){b.cssfallback(f,c,a)}};lsloader.runjs=function(f,c,e){if(!!c&&!!e){for(var b in this.jsRunSequence){if(this.jsRunSequence[b].name==c){this.jsRunSequence[b].code=e}}}if(!!this.jsRunSequence[0]&&!!this.jsRunSequence[0].code&&this.jsRunSequence[0].status!="failed"){var a=document.createElement("script");a.appendChild(document.createTextNode(this.jsRunSequence[0].code));a.type="text/javascript";document.getElementsByTagName("head")[0].appendChild(a);this.jsRunSequence.shift();if(this.jsRunSequence.length>0){this.runjs()}}else{if(!!this.jsRunSequence[0]&&this.jsRunSequence[0].status=="failed"){var d=this;var a=document.createElement("script");a.src=this.jsRunSequence[0].path;a.type="text/javascript";this.jsRunSequence[0].status="loading";a.onload=function(){d.jsRunSequence.shift();if(d.jsRunSequence.length>0){d.runjs()}};document.body.appendChild(a)}}};lsloader.tagLoad=function(b,a){this.jsRunSequence.push({name:a,code:"",path:b,status:"failed"});this.runjs()};lsloader.jsfallback=function(c,b){if(!!this.jsnamemap[b]){return}else{this.jsnamemap[b]=b}for(var a in this.jsRunSequence){if(this.jsRunSequence[a].name==b){this.jsRunSequence[a].code="";this.jsRunSequence[a].status="failed";this.jsRunSequence[a].path=c}}this.runjs()};lsloader.cssfallback=function(e,c,b){if(!!this.cssnamemap[c]){return}else{this.cssnamemap[c]=1}var d=document.createElement("link");d.type="text/css";d.href=e;d.rel="stylesheet";d.onload=d.onerror=b;var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(d,a)};lsloader.runInlineScript=function(c,b){var a=document.getElementById(b).innerText;this.jsRunSequence.push({name:c,code:a});this.runjs()}})();</script>

    <!-- Import queue -->
    <script>function Queue(){this.dataStore=[];this.offer=b;this.poll=d;this.execNext=a;this.debug=false;this.startDebug=c;function b(e){if(this.debug){console.log("Offered a Queued Function.")}if(typeof e==="function"){this.dataStore.push(e)}else{console.log("You must offer a function.")}}function d(){if(this.debug){console.log("Polled a Queued Function.")}return this.dataStore.shift()}function a(){var e=this.poll();if(e!==undefined){if(this.debug){console.log("Run a Queued Function.")}e()}}function c(){this.debug=true}}var queue=new Queue();</script>

    <!-- Import CSS -->
    
        <style id="material_css"></style><script>if(typeof window.lsLoadCSSMaxNums === "undefined")window.lsLoadCSSMaxNums = 0;window.lsLoadCSSMaxNums++;lsloader.load("material_css","/css/material.min.css?Z7a72R1E4SxzBKR/WGctOA==",function(){if(typeof window.lsLoadCSSNums === "undefined")window.lsLoadCSSNums = 0;window.lsLoadCSSNums++;if(window.lsLoadCSSNums == window.lsLoadCSSMaxNums)document.documentElement.style.display="";}, false)</script>
        <style id="style_css"></style><script>if(typeof window.lsLoadCSSMaxNums === "undefined")window.lsLoadCSSMaxNums = 0;window.lsLoadCSSMaxNums++;lsloader.load("style_css","/css/style.min.css?NKhlKQkXw/c66TR5p4wO+w==",function(){if(typeof window.lsLoadCSSNums === "undefined")window.lsLoadCSSNums = 0;window.lsLoadCSSNums++;if(window.lsLoadCSSNums == window.lsLoadCSSMaxNums)document.documentElement.style.display="";}, false)</script>

        

    

    

    <!-- Config CSS -->

<!-- Other Styles -->
<style>
  body, html {
    font-family: Roboto, "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
    overflow-x: hidden !important;
  }
  
  code {
    font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
  }

  a {
    color: #00838F;
  }

  .mdl-card__media,
  #search-label,
  #search-form-label:after,
  #scheme-Paradox .hot_tags-count,
  #scheme-Paradox .sidebar_archives-count,
  #scheme-Paradox .sidebar-colored .sidebar-header,
  #scheme-Paradox .sidebar-colored .sidebar-badge{
    background-color: #0097A7 !important;
  }

  /* Sidebar User Drop Down Menu Text Color */
  #scheme-Paradox .sidebar-colored .sidebar-nav>.dropdown>.dropdown-menu>li>a:hover,
  #scheme-Paradox .sidebar-colored .sidebar-nav>.dropdown>.dropdown-menu>li>a:focus {
    color: #0097A7 !important;
  }

  #post_entry-right-info,
  .sidebar-colored .sidebar-nav li:hover > a,
  .sidebar-colored .sidebar-nav li:hover > a i,
  .sidebar-colored .sidebar-nav li > a:hover,
  .sidebar-colored .sidebar-nav li > a:hover i,
  .sidebar-colored .sidebar-nav li > a:focus i,
  .sidebar-colored .sidebar-nav > .open > a,
  .sidebar-colored .sidebar-nav > .open > a:hover,
  .sidebar-colored .sidebar-nav > .open > a:focus,
  #ds-reset #ds-ctx .ds-ctx-entry .ds-ctx-head a {
    color: #0097A7 !important;
  }

  .toTop {
    background: #757575 !important;
  }

  .material-layout .material-post>.material-nav,
  .material-layout .material-index>.material-nav,
  .material-nav a {
    color: #757575;
  }

  #scheme-Paradox .MD-burger-layer {
    background-color: #757575;
  }

  #scheme-Paradox #post-toc-trigger-btn {
    color: #757575;
  }

  .post-toc a:hover {
    color: #00838F;
    text-decoration: underline;
  }

</style>


<!-- Theme Background Related-->

    <style>
      body{
        background-color: #F5F5F5;
      }

      /* blog_info bottom background */
      #scheme-Paradox .material-layout .something-else .mdl-card__supporting-text{
        background-color: #fff;
      }
    </style>




<!-- Fade Effect -->

    <style>
      .fade {
        transition: all 800ms linear;
        -webkit-transform: translate3d(0,0,0);
        -moz-transform: translate3d(0,0,0);
        -ms-transform: translate3d(0,0,0);
        -o-transform: translate3d(0,0,0);
        transform: translate3d(0,0,0);
        opacity: 1;
      }

      .fade.out{
        opacity: 0;
      }
    </style>


<!-- Import Font -->
<!-- Import Roboto -->

    <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet">


<!-- Import Material Icons -->


    <style id="material_icons"></style><script>if(typeof window.lsLoadCSSMaxNums === "undefined")window.lsLoadCSSMaxNums = 0;window.lsLoadCSSMaxNums++;lsloader.load("material_icons","/css/material-icons.css?pqhB/Rd/ab0H2+kZp0RDmw==",function(){if(typeof window.lsLoadCSSNums === "undefined")window.lsLoadCSSNums = 0;window.lsLoadCSSNums++;if(window.lsLoadCSSNums == window.lsLoadCSSMaxNums)document.documentElement.style.display="";}, false)</script>




    <!-- Import jQuery -->
    
        <script>lsloader.load("jq_js","/js/jquery.min.js?qcusAULNeBksqffqUM2+Ig==", true)</script>
    

    <!-- WebAPP Icons -->
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="application-name" content="android开发者">
    <meta name="msapplication-starturl" content="http://www.xincc.top/2017/03/15/java/JVM学习02-GC算法与种类/">
    <meta name="msapplication-navbutton-color" content="#0097A7">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-title" content="android开发者">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="apple-touch-icon" href="/img/favicon.png">

    <!-- Site Verification -->
    
    

    <!-- RSS -->
    

    <!-- The Open Graph protocol -->
    <meta property="og:url" content="http://www.xincc.top/2017/03/15/java/JVM学习02-GC算法与种类/">
    <meta property="og:type" content="blog">
    <meta property="og:title" content="JVM学习02-GC算法与种类 | android开发者">
    <meta property="og:image" content="/img/favicon.png">
    <meta property="og:description" content="android开发工程师，学习，记录。">
    <meta property="og:article:tag" content="java"> 

    
        <meta property="article:published_time" content="Wed Mar 15 2017 12:00:34 GMT+0800">
        <meta property="article:modified_time" content="Sun May 06 2018 16:42:00 GMT+0800">
    

    <!-- The Twitter Card protocol -->
    <meta name="twitter:card" content="summary_large_image">

    <!-- Add canonical link for SEO -->
    
        <link rel="canonical" href="http://www.xincc.top/2017/03/15/java/JVM学习02-GC算法与种类/index.html" />
    

    <!-- Structured-data for SEO -->
    
        


<script type="application/ld+json">
{
    "@context": "https://schema.org",
    "@type": "BlogPosting",
    "mainEntityOfPage": "http://www.xincc.top/2017/03/15/java/JVM学习02-GC算法与种类/index.html",
    "headline": "JVM学习02-GC算法与种类",
    "datePublished": "Wed Mar 15 2017 12:00:34 GMT+0800",
    "dateModified": "Sun May 06 2018 16:42:00 GMT+0800",
    "author": {
        "@type": "Person",
        "name": "xinwii",
        "image": {
            "@type": "ImageObject",
            "url": "/img/avatar.png"
        },
        "description": "Hi, nice to meet you"
    },
    "publisher": {
        "@type": "Organization",
        "name": "android开发者",
        "logo": {
            "@type":"ImageObject",
            "url": "/img/favicon.png"
        }
    },
    "keywords": ",javaandroid",
    "description": "android开发工程师，学习，记录。",
}
</script>


    

    <!-- Analytics -->
    
    
        <script>
    var _hmt = _hmt || [];
    (function() {var hm = document.createElement('script');
    hm.src = 'https://hm.baidu.com/hm.js?ee8e425850499b806260824b0147ff70';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    

    <!-- Custom Head -->
    

</head>


    
        <body id="scheme-Paradox" class="lazy">
            <div class="material-layout  mdl-js-layout has-drawer is-upgraded">
                

                <!-- Main Container -->
                <main class="material-layout__content" id="main">

                    <!-- Top Anchor -->
                    <div id="top"></div>

                    
                        <!-- Hamburger Button -->
                        <button class="MD-burger-icon sidebar-toggle">
                            <span class="MD-burger-layer"></span>
                        </button>
                    

                    <!-- Post TOC -->

    
    <!-- Back Button -->
    <!--
    <div class="material-back" id="backhome-div" tabindex="0">
        <a class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon"
           href="#" onclick="window.history.back();return false;"
           target="_self"
           role="button"
           data-upgraded=",MaterialButton,MaterialRipple">
            <i class="material-icons" role="presentation">arrow_back</i>
            <span class="mdl-button__ripple-container">
                <span class="mdl-ripple"></span>
            </span>
        </a>
    </div>
    -->


    <!-- Left aligned menu below button -->
    
    
    <button id="post-toc-trigger-btn"
        class="mdl-button mdl-js-button mdl-button--icon">
        <i class="material-icons">format_list_numbered</i>
    </button>

    <ul class="post-toc-wrap mdl-menu mdl-menu--bottom-left mdl-js-menu mdl-js-ripple-effect" for="post-toc-trigger-btn" style="max-height:80vh; overflow-y:scroll;">
        <ol class="post-toc"><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#JVM学习02-GC算法与种类"><span class="post-toc-number">1.</span> <span class="post-toc-text">JVM学习02-GC算法与种类</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#1-GC-简介"><span class="post-toc-number">2.</span> <span class="post-toc-text">1. GC 简介</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#2-GC-算法"><span class="post-toc-number">3.</span> <span class="post-toc-text">2. GC 算法</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-1-引用计数法"><span class="post-toc-number">3.1.</span> <span class="post-toc-text">2.1 引用计数法</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-2-标记-清除"><span class="post-toc-number">3.2.</span> <span class="post-toc-text">2.2 标记-清除</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-3-标记-压缩"><span class="post-toc-number">3.3.</span> <span class="post-toc-text">2.3 标记-压缩</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-4-复制算法"><span class="post-toc-number">3.4.</span> <span class="post-toc-text">2.4 复制算法</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-5-增量算法"><span class="post-toc-number">3.5.</span> <span class="post-toc-text">2.5 增量算法</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#2-6-总结"><span class="post-toc-number">3.6.</span> <span class="post-toc-text">2.6 总结</span></a></li></ol></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#3-分代思想"><span class="post-toc-number">4.</span> <span class="post-toc-text">3. 分代思想</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#4-对象的可触及性"><span class="post-toc-number">5.</span> <span class="post-toc-text">4. 对象的可触及性</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#5-Stop-The-World-STW-现象"><span class="post-toc-number">6.</span> <span class="post-toc-text">5. Stop-The-World (STW) 现象</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#6-垃圾回收器的种类"><span class="post-toc-number">7.</span> <span class="post-toc-text">6. 垃圾回收器的种类</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#6-1-新生代串行收集器"><span class="post-toc-number">7.1.</span> <span class="post-toc-text">6.1 新生代串行收集器</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#6-2-老年代串行收集器"><span class="post-toc-number">7.2.</span> <span class="post-toc-text">6.2 老年代串行收集器</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#6-3-并行收集器"><span class="post-toc-number">7.3.</span> <span class="post-toc-text">6.3 并行收集器</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#6-4-新生代并行回收收集器"><span class="post-toc-number">7.4.</span> <span class="post-toc-text">6.4 新生代并行回收收集器</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#6-5-老年代并行回收收集器"><span class="post-toc-number">7.5.</span> <span class="post-toc-text">6.5 老年代并行回收收集器</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#6-6-CMS收集器"><span class="post-toc-number">7.6.</span> <span class="post-toc-text">6.6 CMS收集器</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#6-7-G1收集器"><span class="post-toc-number">7.7.</span> <span class="post-toc-text">6.7 G1收集器</span></a></li></ol></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#7-GC-相关的参数"><span class="post-toc-number">8.</span> <span class="post-toc-text">7. GC 相关的参数</span></a></li></ol>
    </ul>
    




<!-- Layouts -->

    <!-- Post Module -->
    <div class="material-post_container">

        <div class="material-post mdl-grid">
            <div class="mdl-card mdl-shadow--4dp mdl-cell mdl-cell--12-col">

                <!-- Post Header(Thumbnail & Title) -->
                
    <!-- Paradox Post Header -->
    
        
            <!-- Random Thumbnail -->
            <div class="post_thumbnail-random mdl-card__media mdl-color-text--grey-50">
            <script type="text/ls-javascript" id="post-thumbnail-script">
    var randomNum = Math.floor(Math.random() * 19 + 1);

    $('.post_thumbnail-random').attr('data-original', '/img/random/material-' + randomNum + '.png');
    $('.post_thumbnail-random').addClass('lazy');
</script>

        
    
            <p class="article-headline-p">
                JVM学习02-GC算法与种类
            </p>
        </div>





                
                    <!-- Paradox Post Info -->
                    <div class="mdl-color-text--grey-700 mdl-card__supporting-text meta">

    <!-- Author Avatar -->
    <div id="author-avatar">
        <img src="/img/avatar.png" width="44px" height="44px" alt="Author Avatar"/>
    </div>
    <!-- Author Name & Date -->
    <div>
        <strong>xinwii</strong>
        <span>3月 15, 2017</span>
    </div>

    <div class="section-spacer"></div>

    <!-- Favorite -->
    <!--
        <button id="article-functions-like-button" class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon btn-like">
            <i class="material-icons" role="presentation">favorite</i>
            <span class="visuallyhidden">favorites</span>
        </button>
    -->

    <!-- Qrcode -->
    

    <!-- Tags (bookmark) -->
    
    <button id="article-functions-viewtags-button" class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon">
        <i class="material-icons" role="presentation">bookmark</i>
        <span class="visuallyhidden">bookmark</span>
    </button>
    <ul class="mdl-menu mdl-menu--bottom-right mdl-js-menu mdl-js-ripple-effect" for="article-functions-viewtags-button">
        <li class="mdl-menu__item">
        <a class="post_tag-link" href="/tags/java/">java</a>
    </ul>
    

    <!-- Share -->
    
        <button id="article-fuctions-share-button" class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon">
    <i class="material-icons" role="presentation">share</i>
    <span class="visuallyhidden">share</span>
</button>
<ul class="mdl-menu mdl-menu--bottom-right mdl-js-menu mdl-js-ripple-effect" for="article-fuctions-share-button">
    
    <!-- Leancloud Views -->
        <a class="post_share-link" href="#">
            <li class="mdl-menu__item">
                <span id="/2017/03/15/java/JVM学习02-GC算法与种类/" class="leancloud-views_num" data-flag-title="JVM学习02-GC算法与种类">
     &nbsp;浏览量
</span>

            </li>
        </a>
    

    

    <!-- Share Weibo -->
    
        <a class="post_share-link" href="http://service.weibo.com/share/share.php?appkey=&title=JVM学习02-GC算法与种类&url=http://www.xincc.top/2017/03/15/java/JVM学习02-GC算法与种类/index.html&pic=http://www.xincc.top/img/favicon.png&searchPic=false&style=simple" target="_blank">
            <li class="mdl-menu__item">
                分享到微博
            </li>
        </a>
    

    <!-- Share Twitter -->
    
        <a class="post_share-link" href="https://twitter.com/intent/tweet?text=JVM学习02-GC算法与种类&url=http://www.xincc.top/2017/03/15/java/JVM学习02-GC算法与种类/index.html&via=xinwii" target="_blank">
            <li class="mdl-menu__item">
                分享到 Twitter
            </li>
        </a>
    

    <!-- Share Facebook -->
    
        <a class="post_share-link" href="https://www.facebook.com/sharer/sharer.php?u=http://www.xincc.top/2017/03/15/java/JVM学习02-GC算法与种类/index.html" target="_blank">
            <li class="mdl-menu__item">
                分享到 Facebook
            </li>
        </a>
    

    <!-- Share Google+ -->
    
        <a class="post_share-link" href="https://plus.google.com/share?url=http://www.xincc.top/2017/03/15/java/JVM学习02-GC算法与种类/index.html" target="_blank">
            <li class="mdl-menu__item">
                分享到 Google+
            </li>
        </a>
    

    <!-- Share LinkedIn -->
    

    <!-- Share QQ -->
    

    <!-- Share Telegram -->
    
</ul>

    
</div>

                

                <!-- Post Content -->
                <div id="post-content" class="mdl-color-text--grey-700 mdl-card__supporting-text fade out">
    
        <p>[TOC]</p>
<h1 id="JVM学习02-GC算法与种类"><a href="#JVM学习02-GC算法与种类" class="headerlink" title="JVM学习02-GC算法与种类"></a>JVM学习02-GC算法与种类</h1><h1 id="1-GC-简介"><a href="#1-GC-简介" class="headerlink" title="1. GC 简介"></a>1. GC 简介</h1><p><code>GC（Garbage Collection）</code> 是垃圾收集的简写，GC机制是java中一个比较重要的概念。java的内存管理提供了内存的分配和释放，内存处理是程序编写人员很容易出错的地方，忘记或错误的内存回收很容易导致系统的不稳定，甚至瘫痪。java的GC机制可以很好的检测对象是否超过作用域而可以达到回收的要求，从而实现自动回收垃圾对象的释放内存的目的。</p>
<p>其实早在很久以前（1960）就已经有了GC的概念，只是java借用这个优秀的思想，在java内存模型中，GC的工作区域主要是在堆区域和方法区，大部分都是在堆区域中。
   　　 </p>
<h1 id="2-GC-算法"><a href="#2-GC-算法" class="headerlink" title="2. GC 算法"></a>2. GC 算法</h1><h2 id="2-1-引用计数法"><a href="#2-1-引用计数法" class="headerlink" title="2.1 引用计数法"></a>2.1 引用计数法</h2><p>首先呢，java并没有采用引用计数法作为GC算法，因为它有明显的缺陷。</p>
<p>引用计数法实现比较简单：对于一个对象A来说，只要有任何一个对象或者引用指向了A，那么A的计数器就加1，当引用失效时，引用计数器就减1，最后只要对象A的引用计数器的值为0，那么A就不可能再被使用，就可被视为垃圾。</p>
<p><img src="http://img.blog.csdn.net/20160103231422234" alt="这里写图片描述"></p>
<p>引用计数法存在明显的缺陷，第一由于不断引用和去除引用伴随着加减法，影响性能。第二最大是问题就是很难解决循环引用的问题。</p>
<p><img src="http://img.blog.csdn.net/20160103231439294" alt="这里写图片描述"></p>
<p>这样就会存在很多的对象无法被回收，所以JVM压根没有使用引用计数法作为GC算法。</p>
<h2 id="2-2-标记-清除"><a href="#2-2-标记-清除" class="headerlink" title="2.2 标记-清除"></a>2.2 标记-清除</h2><p>　　<code>标记清除（Mark-Sweep）</code>算法是现代垃圾回收算法的基础。顾名思义，标记清除算法将垃圾清除分为两个阶段：标记和清除</p>
<ul>
<li><code>标记：</code>通过根节点，标记所有从根节点开始的可达对象。因此，未被标记的对象就是未被引用即不可达的对象。</li>
<li><code>清除：</code>清除所有未被标记的对象。</li>
</ul>
<p><img src="http://img.blog.csdn.net/20160103231615085" alt="这里写图片描述"></p>
<h2 id="2-3-标记-压缩"><a href="#2-3-标记-压缩" class="headerlink" title="2.3 标记-压缩"></a>2.3 标记-压缩</h2><p><code>标记压缩（Mark-Compact）</code>算法适用于存活对象比较多的场合，比如老年代。它在标记-清除算法基础上做了一些优化，标记压缩算法和标记清除算法一样，首先通过根节点标记可达的对象，然后还将所有可达的对象（存活的对象）压缩到内存一端，然后清理边界外所有空间。</p>
<ul>
<li><code>标记：</code>通过根节点标记可达的对象。</li>
<li><code>压缩：</code>将存活的对象整理到内存一端，清理边界外所有空间。</li>
</ul>
<p><img src="http://img.blog.csdn.net/20160103231717923" alt="这里写图片描述"></p>
<h2 id="2-4-复制算法"><a href="#2-4-复制算法" class="headerlink" title="2.4 复制算法"></a>2.4 复制算法</h2><p>与标记清除算法相比，<code>复制（Copying）</code>算法相对是一个比较高效的算法，由于涉及到存活对象的赋值，所以复制算法不适合存活对象比较多的场合（如不适合老年代）。复制算法的思想大致如下：将原有的内存分为两块空间，每次只使用其中一块，在垃圾回收的时候，将正在使用内存中存活的对象复制到未使用的内存块中，之后清除正在使用内存中的所有对象，然后交换两个内存的角色完成垃圾回收。</p>
<p><img src="http://img.blog.csdn.net/20160103231739370" alt="这里写图片描述"></p>
<h2 id="2-5-增量算法"><a href="#2-5-增量算法" class="headerlink" title="2.5 增量算法"></a>2.5 增量算法</h2><p>还有一种算法是<code>增量算法</code>（直接摘抄了）：增量算法的基本思想是，如果一次性将所有的垃圾进行处理，需要造成系统长时间的停顿，那么就可以让垃圾收集线程和应用程序线程交替执行。每次，垃圾收集线程只收集一小片区域的内存空间，接着切换到应用程序线程。依次反复，直到垃圾收集完成。使用这种方式，由于在垃圾回收过程中，间断性地还执行了应用程序代码，所以能减少系统的停顿时间。但是，因为线程切换和上下文转换的消耗，会使得垃圾回收的总体成本上升，造成系统吞吐量的下降。</p>
<h2 id="2-6-总结"><a href="#2-6-总结" class="headerlink" title="2.6 总结"></a>2.6 总结</h2><ol>
<li>首先是引用计数法，这个缺陷比较明显，JVM也没有采用，不做讨论。</li>
<li>标记清除和标记压缩相比，前者产生大量不连续的内存碎片。后者虽然不产内存碎片，但是在前者的基础上还进行对象的压缩（整理），所以成本相对较高。且两者都会进行标记和清除，效率不是很高。</li>
<li>复制算法虽然比较简单高效，且不会产生内存碎片，但是明显浪费了大量的内存空间</li>
</ol>
<h1 id="3-分代思想"><a href="#3-分代思想" class="headerlink" title="3. 分代思想"></a>3. 分代思想</h1><p>根据GC算法的总结可以知道，结合不同算法的优点才能规划出一套比较可行的方案，所谓没有最好只有更好。</p>
<p>前面JVM内存模型中有说到将JAVA堆分为<code>新生代</code>和<code>老年代</code>，然后又将新生代细分为<code>eden space</code>，<code>survivor space(分为from和to或者s0和s1)</code>，然后根据对象的存活周期将短命对象归为新生代，长命对象归为老年代。</p>
<p><strong>所以根据不同代的特点，在对象存活比较少的新生代采用<code>复制算法</code>，在老年代采用<code>标记清除</code>或<code>标记压缩</code>算法。</strong></p>
<p><img src="http://img.blog.csdn.net/20160103231843714" alt="这里写图片描述"></p>
<p>图中，在进行垃圾回收的时候，存活对象如何存放有很多种可能。</p>
<ul>
<li><ol>
<li>左边绿色的箭头表示在垃圾回收的时候，第一种年龄比较大的对象会存放在老年代中；第二种情况就是一些比较大的对象无法放到 survivor 空间中，那么此时大对象也被存放到老年代中，所以有时候也称老年代是一个担保空间。</li>
</ol>
</li>
<li><ol start="2">
<li>左边红色和黄色的箭头就是进行正常的复制算法，垃圾回收结束就是右图的样子。</li>
</ol>
</li>
<li><ol start="3">
<li>有的时候查看GC日志的时候，新生代的垃圾回收一般称为minor gc。老年代由于区域比较大且存活对象很多，生命周期很长，所以gc时候会比较长，通常称为full gc。</li>
</ol>
</li>
</ul>
<h1 id="4-对象的可触及性"><a href="#4-对象的可触及性" class="headerlink" title="4. 对象的可触及性"></a>4. 对象的可触及性</h1><p>对象的可触及性顾名思义就是从根节点可以标记的对象。大家一般情况会认为对象要么是可触及的，要么是不可触及的，其实中间还存在一个可复活性。</p>
<ul>
<li><p>可触及性：从根节点可以触及的对象</p>
</li>
<li><p>可复活性：一旦所有引用被释放，对象进入可复活状态，因为在 finalize() 方法后对象可能变得可触及</p>
</li>
<li><p>不可触及性：<code>finalize() 方法</code>之后，对象可能进入不可触及状态。不可触及的对象不能复活，然后进入可回收的状态。 </p>
</li>
</ul>
<p>这里需要注意的一点是 finalize() 方法只会被<strong>执行一次</strong>，所以某个对象不能无限从可复活性到达可触及性。而且 finalize() 方法的执行优先级很低，何时出发GC并不确定，finalize()方法的调用也变得不确定。</p>
<p>更详细参照：<a href="http://blog.csdn.net/pi9nc/article/details/12374049" target="_blank" rel="noopener">《finalize 总结》</a> </p>
<h1 id="5-Stop-The-World-STW-现象"><a href="#5-Stop-The-World-STW-现象" class="headerlink" title="5. Stop-The-World (STW) 现象"></a>5. Stop-The-World (STW) 现象</h1><p><code>STW现象</code>是java的一种全局暂停的现象，所有Java代码停止运行（Native代码可以执行，但不能与JVM交互）。产生这种现象的原因多半是由于 GC 引起的。GC 为什么产生 STW 现象？这个以开 Party 打个比方：我们在开party 的时候会产生很多的垃圾，那么此时如果有人来清理垃圾，我们他在清理的时候，我们又不断产生垃圾，那么房间永远打扫不干净，所以唯一的办法就是我们停止手中的事情，直到房间打扫干净后再进行活动。<br>　　<br>那么GC也是这个道理，当发生GC的时候，必然所有的工作线程会停止，那么此时就会产生java停顿的现象。<br>　　<br>当发生STW现象的时候，如果时间短还好，如果时间特别长甚至几十分钟，服务器就会长时间得不到响应，那么就会带来比较大的危害。解决方法可以使用主备机的切换吧，具体不是很清楚，也不展开了。</p>
<h1 id="6-垃圾回收器的种类"><a href="#6-垃圾回收器的种类" class="headerlink" title="6. 垃圾回收器的种类"></a>6. 垃圾回收器的种类</h1><h2 id="6-1-新生代串行收集器"><a href="#6-1-新生代串行收集器" class="headerlink" title="6.1 新生代串行收集器"></a>6.1 新生代串行收集器</h2><p>串行收集器是一个古老而稳定，经过长时间考验的垃圾收集器。在诸如单 CPU 处理器或者较小的应用内存等硬件平台不是特别优越的场合，它的性能表现可以超过并行回收器和并发回收器。但是有的时候会停顿很长时间，且是线程独占的。</p>
<p>新生代串行收集器采用了<strong>复制算法</strong>，当 JVM 在 Client 模式下运行时，它是默认的垃圾收集器。</p>
<p>在 HotSpot 虚拟机中，使用 <strong>-XX：+UseSerialGC</strong> 参数可以指定使用<code>新生代串行收集器</code>和<code>老年代串行收集器</code>。此时老年代串行收集器采用的是<strong>标记-压缩算法</strong>。</p>
<p><img src="http://img.blog.csdn.net/20160103232129953" alt="这里写图片描述"></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[GC 0.844: [DefNew: 17472K-&gt;2176K(19648K), 0.0188339 secs] 17472K-&gt;2375K(63360K), 0.0189186 secs] [Times: user=0.01 sys=0.00, real=0.02 secs]</span><br></pre></td></tr></table></figure>
<h2 id="6-2-老年代串行收集器"><a href="#6-2-老年代串行收集器" class="headerlink" title="6.2 老年代串行收集器"></a>6.2 老年代串行收集器</h2><p>老年代串行收集器和新生代串行收集器一样，老年代串行收集器采用的是<strong>标记-压缩算法</strong>，可以使用 <strong>-XX：+UseSerialGC</strong> 参数可以指定使用新生代串行收集器和老年代串行收集器。<br>图解和新生代串行收集器一样。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[Full GC 8.259: [Tenured: 43711K-&gt;40302K(43712K), 0.2960477 secs] 63350K-&gt;40302K(63360K), [Perm : 17836K-&gt;17836K(32768K)], 0.2961554 secs] [Times: user=0.28 sys=0.02, real=0.30 secs]</span><br></pre></td></tr></table></figure>
<h2 id="6-3-并行收集器"><a href="#6-3-并行收集器" class="headerlink" title="6.3 并行收集器"></a>6.3 并行收集器</h2><p>并行收集器工作在新生代，仅仅是将新生代串行收集器变成了多线程化了，它的回收策略、算法以及参数和串行回收器一样。<br>新生代依旧采用复制算法，老年代还是串行收集器（标记压缩算法）。GC依旧是线程独占的。<br>开启并行回收器可以使用参数 <strong>-XX:+UseParNewGC</strong></p>
<p><img src="http://img.blog.csdn.net/20160103232240532" alt="这里写图片描述"></p>
<p>多线程并不意味着GC一定会很快，且需要多核CPU的支持才会相对提高效率。<br>可以使用 <strong>-XX:ParallelGCThreads</strong> 限制线程数量</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[GC 0.834: [ParNew: 13184K-&gt;1600K(14784K), 0.0092203 secs] 13184K-&gt;1921K(63936K), 0.0093401 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]</span><br></pre></td></tr></table></figure>
<h2 id="6-4-新生代并行回收收集器"><a href="#6-4-新生代并行回收收集器" class="headerlink" title="6.4 新生代并行回收收集器"></a>6.4 新生代并行回收收集器</h2><p>与 ParNew 类似，新生代并行回收收集器也是使用<strong>复制算法</strong>的收集器。从表面上看，它和并行收集器一样都是多线程、独占式的收集器。但是，并行回收收集器有一个重要的特点：<strong>它非常关注系统的吞吐量</strong>。<br>使用 <strong>-XX:+UseParallelGC</strong> 设置 新生代使用Parallel收集器 + 老年代使用串行收集器<br>使用 <strong>-XX:+UseParallelOldGC</strong> 设置 新生代和老年代都使用Parallel收集器<br><img src="http://img.blog.csdn.net/20160103232330754" alt="这里写图片描述"></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[Full GC [PSYoungGen: 2682K-&gt;0K(19136K)] [ParOldGen: 28035K-&gt;30437K(43712K)] 30717K-&gt;30437K(62848K) [PSPermGen: 10943K-&gt;10928K(32768K)], 0.2902791 secs] [Times: user=1.44 sys=0.03, real=0.30 secs]</span><br></pre></td></tr></table></figure>
<h2 id="6-5-老年代并行回收收集器"><a href="#6-5-老年代并行回收收集器" class="headerlink" title="6.5 老年代并行回收收集器"></a>6.5 老年代并行回收收集器</h2><p>老年代的并行收集器和新生代并行收集器一样，所线程且关注系统吞吐量，采用<strong>标记压缩</strong>的算法。<br>使用 <strong>-XX:+UseParallelOldGC</strong> 设置 新生代和老年代都使用Parallel收集器<br><code>图解和日志清单</code>跟新生代并行收集器一样。</p>
<p>这里新生代和老年代的并行收集器和使用以下参数启动：</p>
<ul>
<li><strong>-XX:MaxGCPauseMills</strong> ： 设置最大的停顿时间，单位是毫秒。GC会尽力保证回收的时间不超过吞吐量。</li>
<li><strong>-XX:GCTimeRatio</strong> ： 设置吞吐量的大小n，GC时间比[ 1/(1+n) ]。默认值为99，即最大允许1%的时间用于垃圾回收。</li>
</ul>
<p>这两个参数本来就是矛盾的，如果将最大停顿时间设置越小，那么GC就会越频繁，从而降低整个系统的吞吐量。如果吞吐量设置越大，GC导致的停顿时间也会越长，所以有所矛盾。所以在实际中也可以采用自适应的GC调节策略，使用 -<strong>XX:+UseAdaptiveSizePolicy</strong> 可以打开自适应 GC 策略。在这种模式下，新生代的大小、eden 和 survivor 的比例、晋升老年代的对象年龄等参数会被自动调整，以达到在堆大小、吞吐量和停顿时间之间的平衡点。在手工调优比较困难的场合，可以直接使用这种自适应的方式，仅指定虚拟机的最大堆、目标的吞吐量 (GCTimeRatio) 和停顿时间 (MaxGCPauseMills)，让虚拟机自己完成调优工作。</p>
<h2 id="6-6-CMS收集器"><a href="#6-6-CMS收集器" class="headerlink" title="6.6 CMS收集器"></a>6.6 CMS收集器</h2><p><code>CMS （Concurrent Mark Sweep）</code>是并发标记清除的收集器，这里的并发表示可以和用户线程一起工作，且采用<strong>标记清除算法</strong>。</p>
<p>CMS 收集器针是老年代收集器，新生代采用 ParNew 并行收集器。可以使用 <code>-XX:+UseConcMarkSweepGC</code>启动 CMS 收集器。</p>
<p>CMS 工作大致可分为如下几个过程：</p>
<ol>
<li>初始标记：GC 线程独占，对根可以直接关联到的对象进行标记，速度比较快。</li>
<li>并发标记：GC 线程和用户线程一起执行，对所有的对象进行标记。</li>
<li>重新标记：由于上一步并发过程，用户线程可能还会生产出垃圾，所以GC 线程独占，在正式清理前重新做一次标记。</li>
<li>并发清除：GC 线程和用户线程一起执行，GC 回收垃圾对象。</li>
</ol>
<p><img src="http://img.blog.csdn.net/20160103232516426" alt="这里写图片描述"></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">1.662: [GC [1 CMS-initial-mark: 28122K(49152K)] 29959K(63936K), 0.0046877 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] </span><br><span class="line">1.666: [CMS-concurrent-mark-start]</span><br><span class="line">1.699: [CMS-concurrent-mark: 0.033/0.033 secs] [Times: user=0.25 sys=0.00, real=0.03 secs] </span><br><span class="line">1.699: [CMS-concurrent-preclean-start]</span><br><span class="line">1.700: [CMS-concurrent-preclean: 0.000/0.000 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] </span><br><span class="line">1.700: [GC[YG occupancy: 1837 K (14784 K)]1.700: [Rescan (parallel) , 0.0009330 secs]1.701: [weak refs processing, 0.0000180 secs] [1 CMS-remark: 28122K(49152K)] 29959K(63936K), 0.0010248 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] </span><br><span class="line">1.702: [CMS-concurrent-sweep-start]</span><br><span class="line">1.739: [CMS-concurrent-sweep: 0.035/0.037 secs] [Times: user=0.11 sys=0.02, real=0.05 secs] </span><br><span class="line">1.739: [CMS-concurrent-reset-start]</span><br><span class="line">1.741: [CMS-concurrent-reset: 0.001/0.001 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]</span><br></pre></td></tr></table></figure>
<p>CMS虽然是并发收集器，但是其实也会存在线程独占的情况导致全局停顿，只是降低了停顿的时间罢了。由于用户线程的运行过程中，GC的时候还需要分CPU去做垃圾回收，这样就会大大降低整体系统的反应速速。在清理阶段，由于和用户线程并发执行，还会产生新的垃圾，导致清理不彻底。甚至还可能会存在产生的垃圾使得CMS来不及清理，让可使用内存的容量迅速减小，直到内存预留不够，引起 concurrent mode failure 错误。</p>
<p>解决方案：</p>
<p><code>第一可以通过 -XX:CMSInitiatingOccupancyFraction 的值来设置触发CMS收集器的阀值。默认为68，即当老年代空间使用率达到68%的时候触发CMS回收。</code><br><code>第二当引起concurrent mode failure 错误的时候，JVM就会启动备用回收器 **老年代串行回收器** 作为GC回收器。</code></p>
<p><strong>CMS收集器的一些参数：</strong></p>
<ol>
<li><code>-XX:+UseCMSCompactAtFullCollection</code> 参数将在进行一个Full GC之后进行一次内存压缩（整理），由于CMS采用的是标记清除算法。由于整理过程是线程独占的，所以可能引起的停顿时间较长。</li>
<li><code>-XX:+CMSFullGCsBeforeCompaction</code> 参数设置多少次Full GC后进行一次内存整理。</li>
<li><code>-XX:ParallelCMSThreads</code> 参数设置CMS线程的数量。</li>
</ol>
<h2 id="6-7-G1收集器"><a href="#6-7-G1收集器" class="headerlink" title="6.7 G1收集器"></a>6.7 G1收集器</h2><p><code>G1 (Garbage-First)</code>是一款面向服务器的垃圾收集器, 主要针对配备多颗处理器及大容量内存的机器. 以极高概率满足GC停顿时间要求的同时,还具备高吞吐量性能特征. 在Oracle JDK 7 update 4 及以上版本中得到完全支持, 专为以下应用程序设计:</p>
<ol>
<li>可以像CMS收集器一样, GC操作与应用的线程一起并发执行</li>
<li>紧凑的空闲内存区间且没有很长的GC停顿时间.</li>
<li>需要可预测的GC暂停耗时.</li>
<li>不想牺牲太多吞吐量性能.</li>
<li>启动后不需要请求更大的Java堆.</li>
</ol>
<p>G1的长期目标是取代CMS(Concurrent Mark-Sweep Collector, 并发标记-清除). 因为特性的不同使G1成为比CMS更好的解决方案. 一个区别是, G1是一款压缩型的收集器，G1通过有效的压缩完全避免了对细微空闲内存空间的分配, 不用依赖于regions，这不仅大大简化了收集器，而且还消除了潜在的内存碎片问题。除压缩以外，G1的垃圾收集停顿也比CMS容易估计，也允许用户自定义所希望的停顿参数(pause targets)。</p>
<p>详细参考博文：<a href="http://blog.csdn.net/renfufei/article/details/41897113" target="_blank" rel="noopener">《G1垃圾收集器入门》</a> </p>
<h1 id="7-GC-相关的参数"><a href="#7-GC-相关的参数" class="headerlink" title="7. GC 相关的参数"></a>7. GC 相关的参数</h1><p><strong>1. 与串行回收器相关的参数</strong></p>
<ul>
<li><p><code>-XX:+UseSerialGC ： 在新生代和老年代使用串行回收器。</code></p>
</li>
<li><p><code>-XX:+SuivivorRatio ： 设置 eden 区大小和 survivor 区大小的比例。8表示 两个Survivor:eden=2:8，即一个Survivor占年轻代的1/10。</code></p>
</li>
<li><p><code>-XX:NewRatio ： 新生代和老年代（不包含永久区）的比。4 表示 新生代:老年代=1:4，即年轻代占堆的1/5。</code></p>
</li>
<li><p><code>-XX:+PretenureSizeThreshold : 设置大对象直接进入老年代的阈值。当对象的大小超过这个值时，将直接在老年代分配。</code></p>
</li>
<li><p><code>-XX:MaxTenuringThreshold : 设置对象进入老年代的年龄的最大值。每一次 Minor GC 后，对象年龄就加 1。任何大于这个年龄的对象，一定会进入老年代。</code></p>
</li>
</ul>
<p><strong>2. 与并行 GC 相关的参数</strong></p>
<ul>
<li><p><code>-XX:+UseParNewGC : 在新生代使用并行收集器。</code></p>
</li>
<li><p><code>-XX:+UseParallelOldGC : 老年代使用并行回收收集器。</code></p>
</li>
<li><p><code>-XX:ParallelGCThreads：设置用于垃圾回收的线程数。通常情况下可以和 CPU 数量相等。但在 CPU 数量比较多的情况下，设置相对较小的数值也是合理的。</code></p>
</li>
<li><p><code>-XX:MaxGCPauseMills：设置最大垃圾收集停顿时间。它的值是一个大于 0 的整数。收集器在工作时，会调整 Java 堆大小或者其他一些参数，尽可能地把停顿时间控制在 MaxGCPauseMills 以内。</code></p>
</li>
<li><p><code>-XX:GCTimeRatio : 设置吞吐量大小，它的值是一个 0-100 之间的整数。假设 GCTimeRatio 的值为 n，那么系统将花费不超过 1/(1+n) 的时间用于垃圾收集。</code></p>
</li>
<li><p><code>-XX:+UseAdaptiveSizePolicy : 打开自适应 GC 策略。在这种模式下，新生代的大小，eden 和 survivor 的比例、晋升老年代的对象年龄等参数会被自动调整，以达到在堆大小、吞吐量和停顿时间之间的平衡点。</code></p>
</li>
</ul>
<p><strong>3. 与 CMS 回收器相关的参数</strong></p>
<ul>
<li><p><code>-XX:+UseConcMarkSweepGC : 新生代使用并行收集器，老年代使用 CMS + 串行收集器（备用收集器）。</code></p>
</li>
<li><p><code>-XX:+ParallelCMSThreads : 设定 CMS 的线程数量。</code></p>
</li>
<li><p><code>-XX:+CMSInitiatingOccupancyFraction : 设置 CMS 收集器在老年代空间被使用多少后触发，默认为 68%。</code></p>
</li>
<li><p><code>-XX:+UseFullGCsBeforeCompaction : 设定进行多少次 CMS 垃圾回收后，进行一次内存压缩。</code></p>
</li>
<li><p><code>-XX:+CMSClassUnloadingEnabled : 允许对类元数据进行回收。</code></p>
</li>
<li><p><code>-XX:+CMSParallelRemarkEndable : 启用并行重标记。</code></p>
</li>
<li><p><code>-XX:CMSInitatingPermOccupancyFraction : 当永久区占用率达到这一百分比后，启动 CMS 回收 (前提是-XX:+CMSClassUnloadingEnabled 激活了)。</code></p>
</li>
<li><p><code>-XX:UseCMSInitatingOccupancyOnly : 表示只在到达阈值的时候，才进行 CMS 回收。</code></p>
</li>
<li><p><code>-XX:+CMSIncrementalMode : 使用增量模式，比较适合单 CPU。</code></p>
</li>
</ul>
<p><strong>4. 与 G1 回收器相关的参数</strong></p>
<ul>
<li><p><code>-XX:+UseG1GC：使用 G1 回收器。</code></p>
</li>
<li><p><code>-XX:+UnlockExperimentalVMOptions : 允许使用实验性参数。</code></p>
</li>
<li><p><code>-XX:+MaxGCPauseMills : 设置最大垃圾收集停顿时间。</code></p>
</li>
<li><p><code>-XX:+GCPauseIntervalMills : 设置停顿间隔时间。</code></p>
</li>
</ul>
<p><strong>5. 其他参数</strong></p>
<ul>
<li><p><code>-XX:+PrintGCDetails ： 打开显示GC日志的开关。</code></p>
</li>
<li><p><code>-XX:+DisableExplicitGC : 禁用显示 GC。</code></p>
</li>
<li><p><code>-Xloggc:Xxx.log : 设置GC的log位置和名称。</code></p>
</li>
<li><p><code>-XX:+HeapDumpOnOutOfMemoryError : 当堆内存移除出错的时候显示最后的GC日志。</code></p>
</li>
<li><p><code>-XX:HeapDumpPath=/var/log/gc/oom-${your-app-name}.hprof: dump的路径</code></p>
</li>
<li><p><code>-Xmx 和 –Xms : 设置堆内存的最大允许值和最小值，如-Xmx32M -Xms32M</code></p>
</li>
<li><p><code>-XX:PermSize 和 -XX:MaxPermSize ： 设置永久代的最小初始值和最大允许值 如-XX:PermSize=64MB 和 -XX:MaxPermSize=256M。</code></p>
</li>
<li><p><code>-XX:MaxPermSize缺省值和client/server选项相关，-server选项下默认MaxPermSize为64m，-client选项下默认MaxPermSize为32m。</code></p>
</li>
<li><p><code>-Xmn ： 设置新生代大小 ， 如 -Xmn16M</code></p>
</li>
</ul>

        
    

    
</div>


                

                <!-- Post Comments -->
                
                    
    <div id="comment" style='padding:10px;' class="vcomment"></div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="//unpkg.com/valine/dist/Valine.min.js"></script>
<script>
    var GUEST_INFO = ['nick','mail','link'];
    var guest_info = 'nick,mail,link'.split(',').filter(function(item){
        return GUEST_INFO.indexOf(item) > -1
    });
    var notify = 'false' == true;
    var verify = 'false' == true;
    new Valine({
        el: '.vcomment',
        notify: notify,
        verify: verify,
        appId: "vEOpfYrMUTPxez4tOTNQJv9A-gzGzoHsz",
        appKey: "qlbEzWd9EJ3vHa07eHpWPIVU",
        placeholder: "Just go go",
        pageSize:'10',
        avatar:'identicon',
        lang:'zh-cn'
    });
</script>

                
            </div>

            <!-- Post Prev & Next Nav -->
            <nav class="material-nav mdl-color-text--grey-50 mdl-cell mdl-cell--12-col">
    <!-- Prev Nav -->
    
        <a href="/2017/03/18/java/JVM学习03-类加载机制/" id="post_nav-newer" class="prev-content">
            <button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon mdl-color--white mdl-color-text--grey-900" role="presentation">
                <i class="material-icons">arrow_back</i>
            </button>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            新篇
        </a>
    

    <!-- Section Spacer -->
    <div class="section-spacer"></div>

    <!-- Next Nav -->
    
        <a href="/2017/03/12/java/JVM学习01-JVM内存模型/" id="post_nav-older" class="next-content">
            旧篇
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon mdl-color--white mdl-color-text--grey-900" role="presentation">
                <i class="material-icons">arrow_forward</i>
            </button>
        </a>
    
</nav>

        </div>
    </div>



                    
                        <!-- Overlay For Active Sidebar -->
<div class="sidebar-overlay"></div>

<!-- Material sidebar -->
<aside id="sidebar" class="sidebar sidebar-colored sidebar-fixed-left" role="navigation">
    <div id="sidebar-main">
        <!-- Sidebar Header -->
        <div class="sidebar-header header-cover" style="background-image: url(/img/sidebar_header.png);">
    <!-- Top bar -->
    <div class="top-bar"></div>

    <!-- Sidebar toggle button -->
    <button type="button" class="sidebar-toggle mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon" style="display: initial;" data-upgraded=",MaterialButton,MaterialRipple">
        <i class="material-icons">clear_all</i>
        <span class="mdl-button__ripple-container">
            <span class="mdl-ripple">
            </span>
        </span>
    </button>

    <!-- Sidebar Avatar -->
    <div class="sidebar-image">
        <img src="/img/avatar.png" alt="xinwii's avatar">
    </div>

    <!-- Sidebar Email -->
    <a data-toggle="dropdown" class="sidebar-brand" href="#settings-dropdown">
        mestic@foxmail.com
        <b class="caret"></b>
    </a>
</div>


        <!-- Sidebar Navigation  -->
        <ul class="nav sidebar-nav">
    <!-- User dropdown  -->
    <li class="dropdown">
        <ul id="settings-dropdown" class="dropdown-menu">
            
                <li>
                    <a href="mailto:mestic@foxmail.com" target="_blank" title="Email Me">
                        
                            <i class="material-icons sidebar-material-icons sidebar-indent-left1pc-element">email</i>
                        
                        Email Me
                    </a>
                </li>
            
        </ul>
    </li>

    <!-- Homepage -->
    
        <li id="sidebar-first-li">
            <a href="/">
                
                    <i class="material-icons sidebar-material-icons">home</i>
                
                主页
            </a>
        </li>
        
    

    <!-- Archives  -->
    
        <li class="dropdown">
            <a href="#" class="ripple-effect dropdown-toggle" data-toggle="dropdown">
                
                    <i class="material-icons sidebar-material-icons">inbox</i>
                
                    归档
                <b class="caret"></b>
            </a>
            <ul class="dropdown-menu">
            <li>
                <a class="sidebar_archives-link" href="/archives/2018/06/">六月 2018<span class="sidebar_archives-count">2</span></a></li><li><a class="sidebar_archives-link" href="/archives/2018/05/">五月 2018<span class="sidebar_archives-count">2</span></a></li><li><a class="sidebar_archives-link" href="/archives/2018/04/">四月 2018<span class="sidebar_archives-count">1</span></a></li><li><a class="sidebar_archives-link" href="/archives/2018/01/">一月 2018<span class="sidebar_archives-count">2</span></a></li><li><a class="sidebar_archives-link" href="/archives/2017/08/">八月 2017<span class="sidebar_archives-count">1</span></a></li><li><a class="sidebar_archives-link" href="/archives/2017/06/">六月 2017<span class="sidebar_archives-count">3</span></a></li><li><a class="sidebar_archives-link" href="/archives/2017/04/">四月 2017<span class="sidebar_archives-count">1</span></a></li><li><a class="sidebar_archives-link" href="/archives/2017/03/">三月 2017<span class="sidebar_archives-count">8</span></a></li><li><a class="sidebar_archives-link" href="/archives/2017/01/">一月 2017<span class="sidebar_archives-count">1</span></a></li><li><a class="sidebar_archives-link" href="/archives/2016/12/">十二月 2016<span class="sidebar_archives-count">1</span></a></li><li><a class="sidebar_archives-link" href="/archives/2016/01/">一月 2016<span class="sidebar_archives-count">6</span></a>
            </ul>
        </li>
        
    

    <!-- Categories  -->
    
        <li class="dropdown">
            <a href="#" class="ripple-effect dropdown-toggle" data-toggle="dropdown">
                
                    <i class="material-icons sidebar-material-icons">chrome_reader_mode</i>
                
                分类
                <b class="caret"></b>
            </a>
            <ul class="dropdown-menu">
                <li>
                <a class="sidebar_archives-link" href="/categories/android/">android<span class="sidebar_archives-count">2</span></a></li><li><a class="sidebar_archives-link" href="/categories/java/">java<span class="sidebar_archives-count">18</span></a></li><li><a class="sidebar_archives-link" href="/categories/mysql/">mysql<span class="sidebar_archives-count">1</span></a></li><li><a class="sidebar_archives-link" href="/categories/weex/">weex<span class="sidebar_archives-count">1</span></a>
            </ul>
        </li>
        
            <li class="divider"></li>
        
    

    <!-- Pages  -->
    
        <li>
            <a href="/about" title="关于我">
                
                    <i class="material-icons sidebar-material-icons">person</i>
                
                关于我
            </a>
        </li>
        
    

    <!-- Article Number  -->
    
</ul>


        <!-- Sidebar Footer -->
        <!--
I'm glad you use this theme, the development is no so easy, I hope you can keep the copyright, I will thank you so much.
If you still want to delete the copyrights, could you still retain the first one? Which namely "Theme Material"
It will not impact the appearance and can give developers a lot of support :)

很高兴您使用并喜欢该主题，开发不易 十分谢谢与希望您可以保留一下版权声明。
如果您仍然想删除的话 能否只保留第一项呢？即 "Theme Material"
它不会影响美观并可以给开发者很大的支持和动力。 :)
-->

<!-- Sidebar Divider -->

    <div class="sidebar-divider"></div>


<!-- Theme Material -->

    <a href="https://github.com/viosey/hexo-theme-material"  class="sidebar-footer-text-a" target="_blank">
        <div class="sidebar-text mdl-button mdl-js-button mdl-js-ripple-effect sidebar-footer-text-div" data-upgraded=",MaterialButton,MaterialRipple">
            主题 - Material
            <span class="sidebar-badge badge-circle">i</span>
        </div>
    </a>


<!-- Help & Support -->
<!--

-->

<!-- Feedback -->
<!--

-->

<!-- About Theme -->
<!--

    <a href="https://blog.viosey.com/index.php/Material.html" target="_blank" class="sidebar-footer-text-a">
        <div class="sidebar-text mdl-button mdl-js-button mdl-js-ripple-effect sidebar-footer-text-div" data-upgraded=",MaterialButton,MaterialRipple">
             sidebar.about_theme
            <span class="mdl-button__ripple-container"><span class="mdl-ripple"></span></span></div>
    </a>

-->

    </div>

    <!-- Sidebar Image -->
    

</aside>

                    

                    
                        <!-- Footer Top Button -->
                        <div id="back-to-top" class="toTop-wrap">
    <a href="#top" class="toTop">
        <i class="material-icons footer_top-i">expand_less</i>
    </a>
</div>

                    

                    <!--Footer-->
<footer class="mdl-mini-footer" id="bottom">
    
        <!-- Paradox Footer Left Section -->
        <div class="mdl-mini-footer--left-section sns-list">
    <!-- Twitter -->
    

    <!-- Facebook -->
    

    <!-- Google + -->
    

    <!-- Weibo -->
    

    <!-- Instagram -->
    

    <!-- Tumblr -->
    

    <!-- Github -->
    
        <a href="https://github.com/xinwii" target="_blank">
            <button class="mdl-mini-footer--social-btn social-btn footer-sns-github">
                <span class="visuallyhidden">Github</span>
            </button><!--
     --></a>
    

    <!-- LinkedIn -->
    

    <!-- Zhihu -->
    

    <!-- Bilibili -->
    

    <!-- Telegram -->
    

    <!-- V2EX -->
    

    <!-- Segmentfault -->
    

    <p>Hosted by <a href="https://pages.coding.me" style="font-weight: bold">Coding Pages</a></p>
</div>


        <!--Copyright-->
        <div id="copyright">
            Copyright&nbsp;©&nbsp;<span year></span>&nbsp;android开发者
            
        </div>

        <!-- Paradox Footer Right Section -->

        <!--
        I am glad you use this theme, the development is no so easy, I hope you can keep the copyright.
        It will not impact the appearance and can give developers a lot of support :)

        很高兴您使用该主题，开发不易，希望您可以保留一下版权声明。
        它不会影响美观并可以给开发者很大的支持。 :)
        -->

        <div class="mdl-mini-footer--right-section">
            <div>
                <div class="footer-develop-div">Powered by Hexo</div>
                <div class="footer-develop-div">Theme - Material</div>
            </div>
        </div>
    
</footer>


                    <!-- Import JS File -->

    <script>lsloader.load("lazyload_js","/js/lazyload.min.js?1BcfzuNXqV+ntF6gq+5X3Q==", true)</script>



    <script>lsloader.load("js_js","/js/js.min.js?V/53wGualMuiPM3xoetD5Q==", true)</script>



    <script>lsloader.load("np_js","/js/nprogress.js?pl3Qhb9lvqR1FlyLUna1Yw==", true)</script>


<script type="text/ls-javascript" id="NProgress-script">
    NProgress.configure({
        showSpinner: true
    });
    NProgress.start();
    $('#nprogress .bar').css({
        'background': '#29d'
    });
    $('#nprogress .peg').css({
        'box-shadow': '0 0 10px #29d, 0 0 15px #29d'
    });
    $('#nprogress .spinner-icon').css({
        'border-top-color': '#29d',
        'border-left-color': '#29d'
    });
    setTimeout(function() {
        NProgress.done();
        $('.fade').removeClass('out');
    }, 800);
</script>





    <!-- Leancloud -->
    <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
    <script>
        AV.initialize('vEOpfYrMUTPxez4tOTNQJv9A-gzGzoHsz', 'qlbEzWd9EJ3vHa07eHpWPIVU');
    </script>
    <script type="text/ls-javascript" id="leancloud-views-script">
    function showTime(Counter) {
        var query = new AV.Query(Counter);
        $('.leancloud-views_num').each(function() {
            var url = $(this).attr('id').trim();
            query.equalTo('url', url);
            query.find({
                success: function(results) {
                    if (results.length === 0) {
                        var content = '0 ' + $(document.getElementById(url)).text();
                        $(document.getElementById(url)).text(content);
                        return;
                    }
                    for (var i = 0; i < results.length; i++) {
                        var object = results[i];
                        var content = object.get('time') + ' ' + $(document.getElementById(url)).text();
                        $(document.getElementById(url)).text(content);
                    }
                },
                error: function(object, error) {
                    console.log('Error: ' + error.code + ' ' + error.message);
                }
            });
        });
    }

    function addCount(Counter) {
      var Counter = AV.Object.extend('Counter');
      url = $('.leancloud-views_num').attr('id').trim();
      title = $('.leancloud-views_num').attr('data-flag-title').trim();
      var query = new AV.Query(Counter);
      query.equalTo('url', url);
      query.find({
          success: function(results) {
            if (results.length > 0) {
                var counter = results[0];
                counter.fetchWhenSave(true);
                counter.increment('time');
                counter.save(null, {
                    success: function(counter) {
                        var content =  counter.get('time') + ' ' + $(document.getElementById(url)).text();
                        $(document.getElementById(url)).text(content);
                    },
                    error: function(counter, error) {
                        console.log('Failed to save Visitor num, with error message: ' + error.message);
                    }
                });
            } else {
              var newcounter = new Counter();
              newcounter.set('title', title);
              newcounter.set('url', url);
              newcounter.set('time', 1);
              newcounter.save(null, {
                  success: function(newcounter) {
                      console.log('newcounter.get(\'time\')='+newcounter.get('time'));
                      var content = newcounter.get('time') + ' ' + $(document.getElementById(url)).text();
                      $(document.getElementById(url)).text(content);
                  },
                  error: function(newcounter, error) {
                      console.log('Failed to create');
                  }
              });
            }
        },
        error: function(error) {
            console.log('Error:' + error.code + ' ' + error.message);
        }
      });
    }
    $(function() {
        var Counter = AV.Object.extend('Counter');
        if ($('.leancloud-views_num').length === 1) {
            addCount(Counter);
        } else if ($('.post-title-link').length > 1) {
            showTime(Counter);
        }
    });
</script>






   





<!-- UC Browser Compatible -->
<script>
	var agent = navigator.userAgent.toLowerCase();
	if(agent.indexOf('ucbrowser')>0) {
		document.write('<link rel="stylesheet" href="/css/uc.css">');
	   alert('由于 UC 浏览器使用极旧的内核，而本网站使用了一些新的特性。\n为了您能更好的浏览，推荐使用 Chrome 或 Firefox 浏览器。');
	}
</script>

<!-- Import prettify js  -->



<!-- Window Load -->
<!-- add class for prettify -->
<script type="text/ls-javascript" id="window-load">
    $(window).on('load', function() {
        // Post_Toc parent position fixed
        $('.post-toc-wrap').parent('.mdl-menu__container').css('position', 'fixed');
    });

    
    
</script>

<!-- MathJax Load-->


<!-- Bing Background -->


<script type="text/ls-javascript" id="lazy-load">
    // Offer LazyLoad
    queue.offer(function(){
        $('.lazy').lazyload({
            effect : 'show'
        });
    });

    // Start Queue
    $(document).ready(function(){
        setInterval(function(){
            queue.execNext();
        },200);
    });
</script>

<!-- Custom Footer -->



<script>
    var copyrightNow = new Date().getFullYear();
    var textContent = document.querySelector('span[year]')

    copyrightSince = 2015;
    if (copyrightSince === copyrightNow||copyrightSince === 0000) {
        textContent.textContent = copyrightNow
    } else {
        textContent.textContent = copyrightSince + ' - ' + copyrightNow
    }

    (function(){
        var scriptList = document.querySelectorAll('script[type="text/ls-javascript"]')

        for (var i = 0; i < scriptList.length; ++i) {
            var item = scriptList[i];
            lsloader.runInlineScript(item.id,item.id);
        }
    })()
console.log('\n %c © Material Theme | Version: 1.5.2 | https://github.com/viosey/hexo-theme-material %c \n', 'color:#455a64;background:#e0e0e0;padding:5px 0;border-top-left-radius:5px;border-bottom-left-radius:5px;', 'color:#455a64;background:#e0e0e0;padding:5px 0;border-top-right-radius:5px;border-bottom-right-radius:5px;');
</script>

                </main>
            </div>
        <script src="/live2dw/lib/L2Dwidget.min.js?0c58a1486de42ac6cc1c59c7d98ae887"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","model":{"scale":1,"hHeadPos":0.5,"vHeadPos":0.618,"jsonPath":"/live2dw/assets/z16.model.json"},"display":{"superSample":2,"width":150,"height":300,"position":"right","hOffset":0,"vOffset":-20},"mobile":{"show":true,"scale":0.1},"react":{"opacityDefault":0.7,"opacityOnHover":0.2}});</script></body>
    
</html>
